package com.tfswx.fljdmxyy.service.impl;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.tfswx.fljdmxyy.constant.SystemConstant;
import com.tfswx.fljdmxyy.dao.RwXtPzMapper;
import com.tfswx.fljdmxyy.dao.RwYxRzMapper;
import com.tfswx.fljdmxyy.model.RwXtPz;
import com.tfswx.fljdmxyy.model.RwYxRz;
import com.tfswx.fljdmxyy.service.TaskService;
import com.tfswx.fljdmxyy.utils.MethodUtils;
import com.tfswx.fljdmxyy.utils.StrUtils;
import com.tfswx.fljdmxyy.utils.UuidUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;


/**
 * 任务服务实现类
 *
 * @Author 陈文佳
 * @Date 2023/03/24
 */
@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Resource
    private RwYxRzMapper rwYxRzMapper;
    @Resource
    private SqlSessionTemplate sqlSessionTemplate;

    /**
     * @MonthName： execute
     * ： 解析器
     * @Author： 陈文佳
     * @Date： 2022/2/25 10:13
     * @Param： [taskServerName]
     * @return： void
     **/
    @Override
    public void execute(RwXtPz task) {
        Date date = new Date();
        Instant start = Instant.now();
        RwYxRz rz = RwYxRz.builder().rzbh(UuidUtils.uuid32()).rwbh(task.getRwbh()).rwmc(task.getRwmc()).rwcs(task.getRwcs())
                          .zxsj(date).zhxgsj(date).cjsj(date).sfcg(SystemConstant.Y).sfsc("N").build();
        try {
            String rwcs = "";
            if (StrUtils.isJSON(task.getRwcs())) {
                rwcs = StringUtils.replace(JSON.toJSONString(MethodUtils.excuteMethod(task.getRwfwm(), task.getRwff(), JSONUtil.parseObj(task.getRwcs()))), "\"", "'");
            } else {
                rz.setSfcg(SystemConstant.N);
                rz.setYcxx("不正确任务参数格式");
            }
            SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession(ExecutorType.BATCH);
            RwXtPzMapper rwXtPzMapper = sqlSession.getMapper(RwXtPzMapper.class);
            task.setRwcs(rwcs);
            rwXtPzMapper.updateRwcs(task);
            sqlSession.flushStatements();
        } catch (Exception e) {
            log.error("===执行任务调度异常，任务服务名称：{}，任务ID：{}，任务名称：{}，异常信息：{}", task.getRwfwm(), task.getRwbh(), task.getRwmc(), e);
            rz.setSfcg(SystemConstant.N);
            rz.setYcxx(e.toString());
        }
        Instant finish = Instant.now();
        long timeElapsed = Duration.between(start, finish).toMillis();
        DecimalFormat df = new DecimalFormat("#.000");
        rz.setZxsc(Double.parseDouble(df.format(timeElapsed * 1000 / 1000)) / 1000);
        rwYxRzMapper.insertRwrz(rz);
    }

}
